{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "notes"
    }
   },
   "source": [
    "## Python 魔法方法与属性\n",
    "\n",
    "\n",
    "python的魔法方法很奇特，有些地方也称他为特殊方法。其结构是由两个下划线（“\\_”开始中间名称最后以两个下划线(\"\\_\")结束的特殊指定方法，这有点类似java中的接口和abstract，是python中定义的一种规则，一种玩法。这也是python与java对于方法重写的一个较大的不同的地方.Java中我们可能会为了实现某种或某类相似的动作行为(action)，从而使用接口式编程，抽象方法来抽象实现过程从而实现其多态性\n",
    "，而且子类(非抽象类)继承了抽象父亲或者实现了接口后，必须要是实现所继承父类或接口的抽象方法，可以明显发现Java中的多态是基于对象的(父类或接口),而python中的“接口实现方式”方式与其有很大的不同，python中的多态是基于动作和特性的实现的，即操作动作决定方法实现，只要对象实现了对应的**魔法方法**就可使用python中的某些特殊操作方式对该对象进行操作，而一般这种”特殊操作“的本质是将其内到python的内建函数的操作中。而内建函数操作的本质是根据区分操作对象的数据结构进行调用的，所以木法方式的作用是通过重写类的魔法方法从而实现将类转化为某类数据结构类型的作用(常见的结构类型有:序列、映射、集合和特殊的结构类型迭代器等）。所以魔法方法的大部分内容是围绕如下几个部分的(类，方法，重写，内建函数，数据结构)来展开的。可以分为如下几个部分进行分段了解:\n",
    "\n",
    "- [内建函数](#1)\n",
    "- [类的方法](#2)\n",
    "- [类的属性](#3)\n",
    "- [魔法方法的使用](#5)\n",
    "- [参考](#7)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "\n",
    "### <a id=\"1\">内建函数</a>\n",
    "\n",
    "python内建函数是一个比较重要的功能，内建函数在某些特定的情况下可以代码的复杂性和增强代码的可读性，内建函数是存在于python的'** __builtins__ **'模块的一些函数，相对于其他模块，存在于'  **__buildins__**'模块的函数与变量并不需要我们通过import导入，属于python内置模块.内建函数的介绍链接[Python 内建函数](https://docs.python.org/2/library/functions.html),也可以借助python本省来了解.可以通过dir(__builtins__)来获取** __builtins__ ** 中的对象和函数:\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "all params of Built-in :\n",
      "\n",
      "['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'dreload', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] \n",
      "\n",
      "Help on built-in function next in module __builtin__:\n",
      "\n",
      "next(...)\n",
      "    next(iterator[, default])\n",
      "    \n",
      "    Return the next item from the iterator. If default is given and the iterator\n",
      "    is exhausted, it is returned instead of raising StopIteration.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print \"all params of Built-in :\\n\"\n",
    "print dir(__builtins__),\"\\n\"#显示__builtins__模块的所有信息\n",
    "\n",
    "#print \"__builtins__ hep info:\\n\"\n",
    "#help(__builtins__) #显示内置函数的基本用法介绍\n",
    "\n",
    "#classmethod  help doc\n",
    "#help(classmethod)   \n",
    "#staticmethod help doc\n",
    "#help(staticmethod)\n",
    "#iter help doc\n",
    "#help(iter)\n",
    "help(next)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "内置函数中有**dir**可以获取python中的模块信息，还有类似**abs**之类的数学计算的函数。如下，仅仅介绍几个和魔法方法y以及和类相关的内置函数:\n",
    "\n",
    "- **classmethod(function)**\n",
    "\n",
    " 将方法function封装成类的方法，被定义成装饰器(decorator),具体实现可以通过两种方式，一种是直接通过装饰器定义，被装饰器修饰的方法会默认被传入该方法，也可以直接通过方法调用实现，与其类似的有staticmethod函数示例如下:\n",
    "   \n",
    "```\n",
    "  class A:\n",
    "  \n",
    "      #装饰器\n",
    "      @classmethod\n",
    "      def methodA(cls,args):\n",
    "           '''method body'''\n",
    "   \n",
    "      def classB(cls):\n",
    "         print \"this is class method\"\n",
    "         \n",
    "      #使用方法调用.\n",
    "      classB=classmethod(classB)\n",
    " \n",
    "```\n",
    "   \n",
    "   \n",
    " -  **staticmethod**\n",
    "   \n",
    "   用法和classmethod基本一致，如下:\n",
    "   \n",
    "   \n",
    "   ```\n",
    "  class A:\n",
    "  \n",
    "      #装饰器\n",
    "      @staticmethod\n",
    "      def methodA(args):\n",
    "           '''method body'''\n",
    "   \n",
    "      def methodB():\n",
    "         print \"this is static method\"\n",
    "         \n",
    "      #使用方法调用.\n",
    "      methodB=classmethod(methodB)\n",
    " \n",
    "```\n",
    "\n",
    "\n",
    "- **iter(source, sentinel=None)**\n",
    "\n",
    "对于iter的介绍，在文档的介绍和python官方文档还是有些区别的，官方doc中的介绍如下:\n",
    "\n",
    "\n",
    "iter(...)\n",
    "    iter(collection) -> iterator\n",
    "    iter(callable, sentinel) -> iterator\n",
    "    \n",
    "    Get an iterator from an object.  In the first form, the argument must\n",
    "    supply its own iterator, or be a sequence.\n",
    "    In the second form, the callable is called until it returns the sentinel.\n",
    "    \n",
    "    \n",
    "对于iter中的第一个参数定位为一个iterator or a sequence，但是在官方doc中有不同的介绍：\n",
    "\n",
    "The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.\n",
    "\n",
    "为此，我进行了一个测试:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[call,her,2]\n",
      "None\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "iter(v, w): v must be callable",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-18-6e1b318bdd62>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      9\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0ma1\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     10\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mB\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"2\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     12\u001b[0m \u001b[0;32mprint\u001b[0m  \u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mTypeError\u001b[0m: iter(v, w): v must be callable"
     ],
     "output_type": "error"
    }
   ],
   "source": [
    "class B(object):\n",
    "    pass\n",
    "\n",
    "class A():\n",
    "     def __call__(self, *args, **kwargs):\n",
    "        print \"[call,her,2]\"\n",
    "        \n",
    "a1=iter(A(),\"a\")\n",
    "print a1.next()\n",
    "b=B()    \n",
    "a=iter(b,\"2\")\n",
    "print  a.next()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如上，可以发现，iter(...)的要求和python官方的doc 要求一致，文档并不能完全介绍完全。当第二参数非空时，需要要求第一参数为实现类迭代功能的对象，如下会介绍(当类实现__iter__方法)，当第二参数存在时，第一个参数必须为可调用对象(实现了__call__方法)。\n",
    "\n",
    "\n",
    "- **len(s)**\n",
    "\n",
    "返回一个对象的长度，传入对象可以是list、string、tuple等，也可以是一个类实现了一个魔法方法(__len__).\n",
    "\n",
    "- **next(...)**\n",
    "\n",
    "返回一个iterator的下一个元素，传入的对象位一个实现了**__next__**方法的对象\n",
    "\n",
    "next(...)\n",
    "    next(iterator[, default])\n",
    "    \n",
    "    Return the next item from the iterator. If default is given and the iterator\n",
    "    is exhausted, it is returned instead of raising StopIteration.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### <a id='2'>类的方法</a>\n",
    "\n",
    "类的方法分为类的创建方法(**__new__**),类的初始化方法(**__init__**),类的方法(**classmethod**),类的静态方法(**staticmethod**),类的方法，类的销毁方法(**__del__**),和类的魔法方法(之后介绍)如下通过一个示例介绍各个类型方法.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "__new__\n",
      "__init__\n",
      "build-in str(o) return \n",
      "Begin transfer-----------------------------call by instance.\n",
      "class method\n",
      "static method\n",
      "this is self\n",
      "Begin transfer------------------------------call by Class\n",
      "class method\n",
      "static method\n",
      "__new__\n",
      "__init__\n",
      "this is self\n",
      "__del__\n",
      "unbound method C() must be called with Base instance as first argument (got nothing instead)\n",
      "__del__\n"
     ]
    }
   ],
   "source": [
    "class Base(object):\n",
    "    'a basic class demo'\n",
    "\n",
    "    def __new__(cls, *args, **kwargs):\n",
    "        print \"__new__\"\n",
    "        return object.__new__(cls,*args, **kwargs)\n",
    "\n",
    "    def __init__(self):\n",
    "        print \"__init__\"\n",
    "\n",
    "\n",
    "\n",
    "    def __del__(self):\n",
    "        print \"__del__\"\n",
    "\n",
    "    @classmethod\n",
    "    def A(cls):\n",
    "        print \"class method\"\n",
    "        \n",
    "        \n",
    "    @staticmethod\n",
    "    def B():\n",
    "        print \"static method\"\n",
    "        \n",
    "        \n",
    "    def C(self):\n",
    "        print \"this is self\"\n",
    "        \n",
    "    def __str__(self):\n",
    "        return \"build-in str(o) return \"\n",
    "        \n",
    "    def __del__(self):\n",
    "        print \"__del__\"\n",
    "        \n",
    "        \n",
    "if __name__==\"__main__\":\n",
    "    a=Base()\n",
    "    print str(a)\n",
    "    try:\n",
    "        print \"Begin transfer-----------------------------call by instance.\"\n",
    "        #call the class method\n",
    "        a.A()\n",
    "        #call static method\n",
    "        a.B()\n",
    "        #call the instance method \n",
    "        a.C()\n",
    "        \n",
    "        print \"Begin transfer------------------------------call by Class\"\n",
    "        # call the class  method\n",
    "        Base.A()\n",
    "        # call static method\n",
    "        Base.B()\n",
    "        #call instance method\n",
    "        Base.C(Base())\n",
    "        #call instance method\n",
    "        Base.C()\n",
    "        pring\n",
    "    except Exception as e:\n",
    "        print e\n",
    "        \n",
    "    del(a)\n",
    "        \n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- ** __new__ ** 方法\n",
    "\n",
    "** __new__  ** 方法是一个静态方法(**同时也是一种魔法方法**)，用于创建一个类的实例，返回一个类的实例对象用于传入初始化方法**_ _init__ ** 中,一般并不需要对其进行声明和重写。若是重写的话，需要注意返回一个有效的类的实例对象,如上实例通过object父类调用类的实例化方法，用于返回一个对象实例。若是不返回一个类的实例对象，会导致类的 **_ _init__  **  方法不会被调用，当然实例(self为空)也不会被成功创建。\n",
    "\n",
    "\n",
    "- ** __init__ ** 方法\n",
    "\n",
    "** __init__ ** 是类创建过程中用的比较多的**魔法方法**，其是类对象创建后调用的初始化方法，紧跟者** __new__ ** 调用后调用，主要用于实例的变量的初始化操作，和传递类创建传入的变量，** __init__ ** 方法可以理解为一个类的实例的构造器，其方法的特点是不会返回任何对象或者值，若返回则会抛出 **TypeError**  异常。\n",
    "\n",
    "\n",
    "- ** __del__** 方法\n",
    "\n",
    "同样属于魔法方法一种。如上，可以发现当我们调用del(a)来销毁实例对象时，会调用该方法，其该属类的实例的析构函数,del内建函数并不会主动调用__del__方法，只有当类的实例对象的引用计数为0时才会被调用,要我们主动显示的调用 **__del__** 方法完成实例的销毁操作.因此，一般不建议重写**__del__** 方法。\n",
    "\n",
    "- ** __str__** 方法\n",
    "\n",
    "用于返回对象的string 字段信息，重写该魔法方法的实例可以通过调用内建函数  **str(o)** 来回调 **__str__** 方法。如上示例有所演示。\n",
    "\n",
    "- ** classmethod ** 方法\n",
    "\n",
    "类的方法，类的方法调用层级归属类级别，其方法定义需要使用 **@classmethod** 装饰或者调用classmethod内建方法来实现，类的方法的第一个参数默认为类的对象,使用**cls** 固定表示，如上的 B方法，类的方法和静态方法一样可以通过类的实例对象调用，也可以直接通过类来调用.\n",
    "\n",
    "\n",
    "- ** staticmethod **方法\n",
    "\n",
    "静态方法，通过装饰器**@staticmethod** 或者内建函数声明使用，静态方法的方法定义部分python的一般函数定义并无不同，页不需要如同classmethod或实例方法一样传入类的对象或实例的对象，其调用和classmethod类似，可以直接通过类调用或者类的实例对象调用。\n",
    "\n",
    "- ** 实例 ** 方法\n",
    "\n",
    "实例方法是归属与创建的实例对象所私有，定义如上def C(self): 其方法需要传入一个实例对象self，且位置为第一个参数，该方法只能由类的实例来调用，不可以通过类直接调用(无参数)，若需要通过类直接调用可以通过绑定式的方式将类的实例对象传入该方法中：** Base.C(Base()) ** 。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "### <a id='3'> 类的属性</a>\n",
    "\n",
    "类的属性部分主要分为两个小部分进行介绍：归属类或实例对象的自定义属性，归属行为特征所共有定义的魔法属性，给出一个简单的例子，根据案例说明。\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a:[CLASS_NAME:Base,instanceCount:1,self.name:a,self.value:10 \n",
      "}\n",
      "\n",
      "b:[CLASS_NAME:Base,instanceCount:2,self.name:b,self.value:12 \n",
      "}\n",
      "\n",
      "{'name': 'b', 'value': 12} \n",
      "\n",
      "{'__dict__': <attribute '__dict__' of 'Base' objects>, '__module__': '__main__', 'instanceCount': 2, '_Base__instance': 12, '_aa': 1234, 'CLASS_NAME': 'Base', '__str__': <function __str__ at 0x7f7a142256e0>, '__weakref__': <attribute '__weakref__' of 'Base' objects>, '__doc__': None, '__init__': <function __init__ at 0x7f7a14190ed8>} \n",
      "\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "type object 'Base' has no attribute '_instance'",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-26-25ca76d45fc7>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     21\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__dict__\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"\\n\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     22\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0mBase\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__dict__\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"\\n\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 23\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mBase\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_instance\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m: type object 'Base' has no attribute '_instance'"
     ],
     "output_type": "error"
    }
   ],
   "source": [
    "class Base(object):\n",
    "    CLASS_NAME=\"Base\"\n",
    "    instanceCount=0\n",
    "    __instance=12\n",
    "    _aa=1234\n",
    "    \n",
    "    def __init__(self,name,value):\n",
    "        Base.instanceCount+=1\n",
    "        self.name=name\n",
    "        self.value=value\n",
    "        \n",
    "    def __str__(self):\n",
    "        return \"CLASS_NAME:%s,instanceCount:%s,self.name:%s,self.value:%s \\n\" % (Base.CLASS_NAME,Base.instanceCount,self.name,self.value)\n",
    "        \n",
    "    \n",
    "a=Base(\"a\",10)\n",
    "print \"a:[%s}\\n\" % str(a)\n",
    "b=Base(\"b\",12)\n",
    "print \"b:[%s}\\n\"% str(b)\n",
    "\n",
    "print b.__dict__,\"\\n\"\n",
    "print Base.__dict__,\"\\n\"\n",
    "print Base._instance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **类的属性**\n",
    "\n",
    "如上，类的属性也可以认为是静态属性，可以直接通过类来调用，CLASS_NAME和instanceCount就是这样的属性.\n",
    "\n",
    "- **实例属性**\n",
    "\n",
    "实例属性是归属于实例对象本身的，需要直接使用实例对象来调用，如上的**self.name**和**self.value**\n",
    "\n",
    "- **“私有属性“**\n",
    "\n",
    "python中并不存在只能从内部访问的私有变量类型，但python代码都遵守的公约规定:带有下划线('_')前缀开头的变量或方法被示为飞公开API的一部分,其有两种情况，一种是前面至少有两个下划线('_')开头，后面之多有一个下划线('_')结束，python对其使用name mangling机制做了一个简单的支持，会将其标识符替换成_className__name,如上**__instance  ** ，另一种是以一个\"_\"开始的变量在被作为一个module导入时，使用 from module import * 后并不可以直接使用其直接使用，还是需要通过类或者实例变量配合使用.\n",
    "\n",
    "- **魔法属性**\n",
    "\n",
    "python中的魔法属性是对类或实例的一些数据的描述整合.如上的\"**__dict__**\"位一个字典映射对象，存储一个类或者实例的可读属性。类似的魔法属性还包括:**__class__*、**__bases__**、**__name__**、**__mro__**、**__subclasses__**等。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a id='5'>魔法方法的使用</a>\n",
    "\n",
    "如上，已经说了不少有关魔法方法的使用，如**__new__**、**__init__**、**__del__**等特定的类生命周期相关的魔法方法，也有功能性的如**__str__**等，如下，就是对于魔法方法做一个扩展性的说明。\n",
    "\n",
    "魔法方法的存在是python的多态性的一种表现，不同其他语言的多态，python的多态更多的表现在动作或者称作功能上，对于想要实现某类功能的类只需要对应实现某些对应的魔法方法，即可通过python的内建函数进行某些特定功能的操作。如常见的求长度、求hash数值、迭代器、生成器的使用。如下，通过一个小的示例来了解一些常用的魔法方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "base __init__\n",
      "True\n",
      "1\n",
      "10\n",
      "[9, 8, 7, 6]\n",
      "Base 海飞\n"
     ]
    }
   ],
   "source": [
    "class Base(object):\n",
    "    def __init__(self):\n",
    "        self.index = 0\n",
    "        print \"base __init__\"\n",
    "\n",
    "    # 返回字符串化\n",
    "    def __str__(self):\n",
    "        return \"Base\"\n",
    "    #\n",
    "    # 返回对象长度\n",
    "    def __len__(self):\n",
    "        return 10\n",
    "\n",
    "    # 返回hash数值\n",
    "    def __hash__(self):\n",
    "        return 199908\n",
    "\n",
    "    # 真值判断\n",
    "    def __nonzero__(self):\n",
    "        return True\n",
    "\n",
    "    # 返回转化成一个unicode对象\n",
    "    def __unicode__(self):\n",
    "        return u'海飞'\n",
    "\n",
    "    # 当查找一个一个属性未查找到时调用\n",
    "    def __getattr(self, name):\n",
    "        if name == \"name\":\n",
    "            return \"hfcai\"\n",
    "        else:\n",
    "            raise Exception(\"No exists tohis attribute.\")\n",
    "\n",
    "    #当尝试给一个属性赋值时调用\n",
    "    def __setattr__(self, name, value):\n",
    "        self.__dict__[name] = value\n",
    "\n",
    "    # 当属性被删除时调用\n",
    "    def __delattr__(self, name):\n",
    "        print \"__delattr__:%s\" % name\n",
    "\n",
    "    # 新式类中访问属性的调用,使用超类的方法防止循环调用\n",
    "    def __getattribute__(self, name):\n",
    "        return super(Base,self).__getattribute__(name)\n",
    "\n",
    "    # 新式类作为描述器\n",
    "    def __get__(self, obj, type=None):\n",
    "        return 'get', self, obj, type\n",
    "\n",
    "    def __set__(self, obj, val):\n",
    "        print 'set', self, obj, val\n",
    "\n",
    "    def __delete__(self, obj):\n",
    "        print 'delete', self, obj\n",
    "    #\n",
    "    #\n",
    "    # 接受self[key]这样的切片操作，一般针对于序列对象\n",
    "    def __getitem__(self, key):\n",
    "        return self.__dict__[key]\n",
    "\n",
    "    def __setitem__(self, key, value):\n",
    "        print \"__setitem__\"\n",
    "\n",
    "    def __delitem__(self, key, value):\n",
    "        print \"__delitem__\"\n",
    "\n",
    "    # 迭代器  ,重写表明当前类的示例为一个迭代器\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    # next\n",
    "    def next(self):\n",
    "        self.index+=1\n",
    "        return self.index\n",
    "\n",
    "    # 返回一个反向的迭代对象\n",
    "    def __reversed__(self):\n",
    "        return [9, 8, 7, 6]\n",
    "\n",
    "    # 含操作\n",
    "    def __contains__(self, item):\n",
    "        return True\n",
    "\n",
    "\n",
    "\n",
    "a = Base()\n",
    "#__contain__\n",
    "print \"test\" in a\n",
    "# __iter__\n",
    "b = iter(a)\n",
    "print b.next()\n",
    "# __len__\n",
    "print len(a)\n",
    "print reversed(a)\n",
    "print str(a),unicode(a)\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如上，涉及到的魔法方法较多，分类讲解一部分的魔法方法，其用法类似:\n",
    "\n",
    "- **普通关联回调内建函数**\n",
    "\n",
    "这种比较简单，在类中重写对应的魔法方法，使用对应的回调返回重写方法的返回值，大多的魔法方法都是这类的，如上**__len__**、**__str__**、**__unicode__**等就属于这类。\n",
    "\n",
    "\n",
    "\n",
    "- **属性相关魔法方法**\n",
    "\n",
    "与属性相关的魔法方法**__getattr__**、**__setattrr__**、**__getitem__**、**___setitem__**、**__getattribute__**，其中**__getitem__**、**___setitem__**属于序列或映射的魔法方法，而**__getattr__**、**__setattrr__**属于获取类中的变量的属性的设置获取调用情况。其中**__getattr__** 属于当类中无法获取该变量时调用，而**__getattribute__**会拦截所有属性的获取。\n",
    "\n",
    "\n",
    "- **描述器**\n",
    "\n",
    "对于实现了**__get__**、**__set__**、**__del__**魔法方法的类可以称之位描述器.同时具有**__get__**和**__set__**方法，这样的descriptor叫做data descriptor，如果只有**__get__**方法，则叫做non-data descriptor。\n",
    "\n",
    "\n",
    "\n",
    "- **迭代器**\n",
    "\n",
    "python中的迭代器是实现了**__iter__**魔法方法的类，并通过实现 **next(self)**方法进行迭代调用，如上示例。\n",
    "\n",
    "\n",
    "- **生成器**\n",
    "\n",
    "python中有一个特别的迭代器，可以通过关键词**yield**进行迭代返回，如下格式:\n",
    "\n",
    "```\n",
    "def reperater(value):\n",
    "    while True:\n",
    "        new = (yield value)\n",
    "        if new is not None:\n",
    "            value=new\n",
    "            \n",
    "            \n",
    "r=repeater(42)\n",
    "r.next()\n",
    "\n",
    "42\n",
    "\n",
    "r.send(\"Hello world!\")\n",
    "\n",
    "\"Hello world!\"\n",
    "```\n",
    "\n",
    "\n",
    "如上demo来自《python基础教程 -生成器》一章的示例，其中包含**yeild**会返回一个对象，并挂起。而在挂起状态可以通过send方法发送一个值，而再次返回发送过的值.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "###  <a id='7'> 参考</a>\n",
    "\n",
    "-  Python基础教程-魔法方法、属性和迭代器\n",
    "-  [Python 在线官方文档](https://docs.python.org/2/index.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
